package com.zs.grain.ui

import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable
import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.MediaController
import com.alibaba.android.arouter.facade.annotation.Route
import com.xnkj1688.semplibrary.mvvm.BaseMvvmFragment
import com.zs.grain.ARouterPath
import com.zs.grain.R
import com.zs.grain.databinding.FragmentAdsBinding

@Route(path = "ARouterPath.AdsFragment")
class AdsFragment : BaseMvvmFragment<FragmentAdsBinding, AdsViewModel>() {
    override val layoutId: Int = R.layout.fragment_ads

    override fun initViewModel(binding: FragmentAdsBinding) {
        binding.vm = this.mViewModel
        binding.view = this
    }

    override fun initAction() {
        super.initAction()
        val media = MediaController(this.context)
        mBinding.videoViewMain.setMediaController(media)
        media.visibility = View.GONE
        mViewModel.init()
    }

    override fun onPause() {
        super.onPause()
    }

    override  fun onResume(){
        super.onResume()

    }

    override fun onUiNotify(name: String, bundle: Bundle) {
        super.onUiNotify(name, bundle)
        when (name) {
            "SwitchUI" -> {
//                var menuNo = bundle.getLong("MenuNo")
//                var activity = this.activity as MainActivity
            }
            "Advertisement" -> {
                var fileName = bundle.getString("FileName")
                play(fileName)
            }
        }
    }

    private fun play(fileName: String) {
        var path = fileName
        if (path.toLowerCase().endsWith(".mov")
            || path.toLowerCase().endsWith(".mkv")
            || path.toLowerCase().endsWith(".mp4")
            || path.toLowerCase().endsWith(".avi")
        ) {
            val uri = Uri.parse(path)
            mBinding.videoViewMain.setVideoURI(uri)
//                    mBinding.videoView.setOnPreparedListener { mediaPlayer -> mediaPlayer.isLooping = true }
            mBinding.videoViewMain.setOnErrorListener { mediaPlayer, i, i1 ->
                mViewModel.onVideoError(mediaPlayer, i, i1)
            }
            mBinding.videoViewMain.setOnCompletionListener {
                mViewModel.onVideoCompletion()
            }
            mBinding.videoViewMain.setBackground(null);
            mBinding.videoViewMain.start()
            mBinding.videoViewMain.requestFocus()
        } else {
            var bitmap = BitmapFactory.decodeFile(path);
            var drawable = BitmapDrawable(this.getResources(), bitmap);
            mBinding.videoViewMain.setBackground(drawable);
        }
    }
}